"""
--------------------------------------------------------------------------------
功能:通过socket获取手持陀螺仪模块数据(打印出来的数据为蓝色字体)
细节:打印出来的数据为陀螺仪的原始数据,包括acc_x,acc_y,acc_z,gyro_x,gyro_y,gyro_z
日期:2025-06-03
作者:Unirobot
QQ交流群:811348489
寄语：代码中能遇见你，真好，有你，真好.
署名：有你同创智能机器人科技(北京)有限公司
--------------------------------------------------------------------------------
"""
#需要用到的库
import socket
import json
import time
from src.arm_control import custom_font


#加载自定义字体库-------------------------------------------------
msg = custom_font.CustomFont()
print(msg.color_text(msg.compony_msg, color="cyan", bold=True))


#配置陀螺仪网络接口参数-----------------------------------------------
HOST = '0.0.0.0'  #监听所有网卡
PORT = 9000       #端口号,与Arduino端保持一致
print(f"[INFO] 启动Socket服务端, 监听端口 {PORT} ...")
print(msg.color_text(msg.imu_load_success, color="cyan", bold=True))
time.sleep(1)

#-------------------------------------------------------------------
"""
------------------------------------------------------------
通过socket监听esp32模块发送的陀螺仪数据, 并将数据在终端打印出来
------------------------------------------------------------
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(1)
    print("[INFO] 等待Arduino客户端连接...")
    conn, addr = s.accept()
    with conn:
        print(f"[INFO] 已连接: {addr}")
        buffer = b''
        while True:
            data = conn.recv(1024)
            if not data:
                print("[WARN] 客户端断开连接")
                break
            buffer += data
            while b'\n' in buffer:
                line, buffer = buffer.split(b'\n', 1)
                try:
                    # 解码陀螺仪数据
                    sensor_data = json.loads(line.decode('utf-8'))
                    #打印陀螺仪原始数据, 天蓝色字体，白色背景，字体加粗
                    print(msg.color_text(sensor_data, color="cyan", bg_color="white", bold=True))
                
                except Exception as e:
                    print(f"[ERROR] 解码失败: {e}")


